<template>
    <div class="uploadImg-box">
        <UploadAttachmentFile
            :show-upload-list="false"
            v-slot="{ fileList, loading }: any"
            @update:upload-file-info-list="hdlDefaultImgFile"
            :multiple="true"
            :before-upload="beforeUpload"
            ref="uploaderRef"
            accept=".png,.jpg,.jpeg,.bmp"
            v-bind="$attrs"
            dir-name="tx/faceLibrary/"
            :axios="axios"
        >
            <div class="uploader-box">
                <div class="uploader" v-if="selectedImgsViews.length > 0">
                    <LoadingOutlined v-if="loading" />
                    <!-- <PlusOutlined v-else /> -->
                    <img class="add-img" src="@/assets/Lw/add-img.png" alt="" />
                    <div class="ant-upload-text">
                        <img src="@/assets/Lw/upload.png" alt="" />
                        <span>上传图片</span>
                    </div>
                </div>
                <div class="uploader2" v-else>
                    <!-- <UploadOutlined style="font-size: 18px" /> -->
                    <img class="add-img" src="@/assets/Lw/add-img.png" alt="" />
                    <div class="name">
                        可拖拽图片至此处，或点击
                        <img src="@/assets/Lw/upload.png" alt="" />
                        <span>上传图片</span>
                    </div>
                    <div class="desc">
                        图片可多选，最多支持上传{{
                            props.uploadNum
                        }}张。支持jpg、png图片格式。单张大小限制在10MB内。
                    </div>
                </div>

                <div
                    v-for="(item, index) in selectedImgsViews"
                    class="exp-img"
                    alt=""
                >
                    <img class="show-img" :src="encodeURI2(item)" alt="" />
                    <div class="operate" @click.stop="hdlRemove(index)">
                        <img src="@/assets/Lw/close.png" alt="" />
                        <!-- <DeleteOutlined @click.stop="hdlRemove(index)" /> -->
                    </div>
                </div>
            </div>
        </UploadAttachmentFile>
        <div class="process-box">
            <div class="process-bg">
                <div class="process" :style="{ width: `${processNum}%` }"></div>
            </div>
            <div class="txt">{{ processNum }}%</div>
        </div>
        <div class="tips" v-show="Number(processNum) == 100">
            图片分析中，请耐心等待...
        </div>
    </div>
</template>

<script setup lang="ts">
    import { computed, ref } from "vue";
    import { FileInfo } from "@/type/mediaSourceManage";
    import globalService from "@/service/global.service";
    import UploadAttachmentFile from "@/components/UploadAttachmentFile/UploadAttachmentFile.vue";
    import { message } from "ant-design-vue";
    import encodeURI2 from "@/utils/encodeURI";
    import axios from "@/service/axios";

    const props = withDefaults(
        defineProps<{
            uploadNum: number;
            initImgUrls: string[];
        }>(),
        {
            uploadNum: 20,
            initImgUrls: () => [],
        },
    );
    const emit = defineEmits(["onSuccess"]);
    const uploaderRef = ref();
    const hdlDefaultImgFile = async (fileList: FileInfo[]) => {
        // let url = await getFixedImgLink(fileList[0].key);
        // menuInfo.value.iconNotActive = url;
    };
    const selectedImgFiles = ref<Array<File | null>>([]);
    const selectedImgsViews = ref<string[]>([]);

    watchEffect(() => {
        selectedImgsViews.value = [...props.initImgUrls];
        let arr = new Array(props.initImgUrls.length)
            .fill(0)
            .map((item) => null);
        selectedImgFiles.value.push(...arr);
    });

    let limitSize = 10 * 1024 * 1024;
    const processNum = ref("0");
    const beforeUpload = (file: any) => {
        if (selectedImgsViews.value.length < props.uploadNum) {
            const { size, name } = file;
            if (size > limitSize) {
                message.error("图片不能大于10MB");
                return false;
            }
            let url = URL.createObjectURL(file);
            selectedImgsViews.value.push(url);
            selectedImgFiles.value.push(file);
        }

        return false;
    };

    const hdlUpload = (cb: (urls: string[]) => void) => {
        let totalSize = selectedImgFiles.value.reduce((total, file) => {
            if (file) {
                const { size } = file;
                total += size;
            }
            return total;
        }, 0);
        let oldPercent = 0;
        let urls: string[] = [];
        let count = 0;
        let selectedImgFilesFilerNull = selectedImgFiles.value.filter((item) =>
            item ? true : false,
        );
        if (selectedImgFilesFilerNull.length > 0) {
            selectedImgFilesFilerNull.forEach((file, i) => {
                uploaderRef.value.hdlUpload({
                    file,
                    onSuccess: async (res: any) => {
                        let res1 = await globalService.link(res.key);
                        let url = res1.data.result.data;
                        urls.push(url);
                        if (count == selectedImgFilesFilerNull.length - 1) {
                            processNum.value = Number(100).toFixed(2);
                            let arr = selectedImgsViews.value.filter((url) =>
                                props.initImgUrls.includes(url),
                            );
                            urls.unshift(...arr);
                            emit("onSuccess", urls);
                            cb && cb(urls);
                        }
                        count += 1;
                    },
                    onProgress: ({ percent, file }: any) => {
                        const { size } = file;
                        let ratio = size / totalSize;
                        oldPercent = percent;
                        // console.log(percent);
                        if (percent == 1) {
                            oldPercent = 0;
                        }
                        percent * ratio;
                        processNum.value = Math.min(
                            Number(processNum.value) +
                                (percent - oldPercent) * ratio * 100,
                            100,
                        ).toFixed(2);
                    },
                });
            });
        } else {
            processNum.value = "100";
            cb(selectedImgsViews.value);
        }
    };

    const hdlRemove = (index: number) => {
        selectedImgsViews.value.splice(index, 1);
        selectedImgFiles.value.splice(index, 1);
    };

    const clearProgress = () => {
        processNum.value = "0";
    };

    defineExpose({
        hdlUpload,
        clearProgress,
        selectedImgsViews,
    });
</script>

<style lang="scss" scoped src="./UploadImg.scss"></style>
